$(document).ready(function(){
  setTimeout(imgs_gray,100)
})

/**
 * 对所有图片进行操作
 */
function imgs_gray() {
  //ie
  $('head').append('<style type="text/css">body { filter: Gray;}</style>');
  //firefox, chrome
  $('img').each(function(){
    try {
      cp_gray_img(this);
      //cp_gray_img(this,1);
    } catch(e){}
    $(this).remove();
  });
}

/**
 * 复制一个灰度图片
 */
function cp_gray_img(obj, g) {
  var obj_img = $(obj).after('<canvas></canvas>');
  var obj_canvas = obj_img.next();
  var canvas = obj_canvas.get(0);
  canvas.width=obj.width;
  canvas.height=obj.height;

  var ctx = canvas.getContext('2d');
  //ctx.drawImage(obj, 0, 0);
  ctx.drawImage(obj, 0,0,obj.width,obj.height, 0,0,canvas.width,canvas.height);
  var canvasData = ctx.getImageData(0, 0, canvas.width, canvas.height);

  for (var x = 0; x < canvas.width; x++) {
    for (var y = 0; y < canvas.height; y++) {
      // Index of the pixel in the array
      var idx = (x + y * canvas.width) * 4;

      // The RGB values
      var r = canvasData.data[idx + 0];
      var g = canvasData.data[idx + 1];
      var b = canvasData.data[idx + 2];

      // Update the values of the pixel;
      if (g==1) {
        var gray = get_gray_data_ave(r,g,b);
      }else{
        var gray = get_gray_data_hls(r,g,b);
      }
      canvasData.data[idx + 0] = gray;
      canvasData.data[idx + 1] = gray;
      canvasData.data[idx + 2] = gray;
    }
  }
  ctx.putImageData(canvasData, 0, 0);
}

/**
 * 算法1（对RGB中的最大和最小值求平均值）
 */
function get_gray_data_hls(r,g,b) {
  return (Math.max(r,g,b)+Math.min(r,g,b)) / 2;
}
/**
 * 算法2（对RGB求平均值）
 */
function get_gray_data_ave(r,g,b) {
  return (r+g+b) / 3;
}